"""
订单相关服务
"""
from datetime import datetime
from app.models.order import Order, OrderItem, OrderStatus
from app.models.product import Product, ProductVariant
from app.models.user import User
from app.extensions import db
from app.utils.errors import NotFoundError, ValidationError

class OrderService:
    """订单服务类"""
    
    @staticmethod
    def get_orders(user_id=None, page=1, per_page=20, status=None, 
                  order_number=None, start_date=None, end_date=None, 
                  sort_by='created_at', sort_order='desc'):
        """获取订单列表"""
        query = Order.query
        
        # 如果提供了用户ID，只返回该用户的订单
        if user_id:
            query = query.filter_by(user_id=user_id)
        
        # 过滤条件
        if status:
            query = query.filter_by(status=status)
        
        if order_number:
            query = query.filter(Order.order_number.ilike(f'%{order_number}%'))
        
        if start_date:
            query = query.filter(Order.created_at >= start_date)
        
        if end_date:
            query = query.filter(Order.created_at <= end_date)
        
        # 排序
        if sort_order == 'desc':
            query = query.order_by(getattr(Order, sort_by).desc())
        else:
            query = query.order_by(getattr(Order, sort_by).asc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page)
        
        return pagination
    
    @staticmethod
    def get_order(order_id, user_id=None):
        """获取订单详情"""
        order = Order.query.get(order_id)
        
        if not order:
            raise NotFoundError("订单不存在")
        
        # 如果提供了用户ID，确保该用户有权限查看此订单
        if user_id and order.user_id != user_id:
            current_user = User.query.get(user_id)
            if not current_user or not current_user.is_admin:
                raise ValidationError("无权限查看此订单")
        
        return order
    
    @staticmethod
    def create_order(user_id, data):
        """创建订单"""
        if not data.get('items') or len(data.get('items')) == 0:
            raise ValidationError("订单商品不能为空")
        
        try:
            # 创建订单
            order = Order(
                user_id=user_id,
                status=OrderStatus.PENDING.value,
                shipping_address=data.get('shipping_address'),
                shipping_method=data.get('shipping_method'),
                payment_method=data.get('payment_method'),
                notes=data.get('notes')
            )
            
            # 生成订单号
            now = datetime.now()
            order.order_number = f"ORD-{now.strftime('%Y%m%d%H%M%S')}-{user_id}"
            
            db.session.add(order)
            db.session.flush()  # 获取订单ID
            
            total_amount = 0
            
            # 添加订单商品
            for item_data in data.get('items'):
                product_id = item_data.get('product_id')
                variant_id = item_data.get('variant_id')
                quantity = item_data.get('quantity', 1)
                
                if variant_id:
                    variant = ProductVariant.query.get(variant_id)
                    if not variant:
                        db.session.rollback()
                        raise ValidationError(f"商品变体ID {variant_id} 不存在")
                    
                    price = variant.price
                    product = variant.product
                else:
                    product = Product.query.get(product_id)
                    if not product:
                        db.session.rollback()
                        raise ValidationError(f"商品ID {product_id} 不存在")
                    
                    price = product.price
                
                # 检查库存
                if variant_id and variant.stock < quantity:
                    db.session.rollback()
                    raise ValidationError(f"商品 '{product.name}' 变体库存不足")
                elif not variant_id and product.stock < quantity:
                    db.session.rollback()
                    raise ValidationError(f"商品 '{product.name}' 库存不足")
                
                # 创建订单项
                order_item = OrderItem(
                    order_id=order.id,
                    product_id=product_id,
                    variant_id=variant_id,
                    quantity=quantity,
                    price=price,
                    subtotal=price * quantity
                )
                
                db.session.add(order_item)
                
                # 更新库存
                if variant_id:
                    variant.stock -= quantity
                else:
                    product.stock -= quantity
                
                # 计算总金额
                total_amount += price * quantity
            
            # 更新订单总金额
            order.total_amount = total_amount
            
            db.session.commit()
            return order
            
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"创建订单失败: {str(e)}")
    
    @staticmethod
    def update_order_status(order_id, status, admin_required=True):
        """更新订单状态"""
        order = Order.query.get(order_id)
        
        if not order:
            raise NotFoundError("订单不存在")
        
        # 验证状态值是否有效
        if status not in [s.value for s in OrderStatus]:
            raise ValidationError("无效的订单状态")
        
        try:
            # 更新状态
            order.status = status
            
            # 根据状态更新相应的时间戳
            now = datetime.now()
            if status == OrderStatus.SHIPPED.value:
                order.shipped_at = now
            elif status == OrderStatus.COMPLETED.value:
                order.completed_at = now
            
            db.session.commit()
            return order
            
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"更新订单状态失败: {str(e)}")
    
    @staticmethod
    def delete_order(order_id):
        """删除订单"""
        order = Order.query.get(order_id)
        
        if not order:
            raise NotFoundError("订单不存在")
        
        try:
            # 恢复库存
            for item in order.items:
                if item.variant_id:
                    variant = ProductVariant.query.get(item.variant_id)
                    if variant:
                        variant.stock += item.quantity
                else:
                    product = Product.query.get(item.product_id)
                    if product:
                        product.stock += item.quantity
            
            db.session.delete(order)
            db.session.commit()
            return {"msg": "订单删除成功"}
            
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"删除订单失败: {str(e)}")
    
    @staticmethod
    def batch_delete_orders(order_ids):
        """批量删除订单"""
        if not order_ids or not isinstance(order_ids, list):
            raise ValidationError("请提供有效的订单ID列表")
        
        try:
            # 获取所有要删除的订单
            orders = Order.query.filter(Order.id.in_(order_ids)).all()
            found_ids = [order.id for order in orders]
            
            # 检查是否所有ID都存在
            missing_ids = [id for id in order_ids if id not in found_ids]
            if missing_ids:
                raise ValidationError(f"部分订单不存在: {missing_ids}")
            
            # 恢复库存并删除订单
            for order in orders:
                for item in order.items:
                    if item.variant_id:
                        variant = ProductVariant.query.get(item.variant_id)
                        if variant:
                            variant.stock += item.quantity
                    else:
                        product = Product.query.get(item.product_id)
                        if product:
                            product.stock += item.quantity
                
                db.session.delete(order)
            
            db.session.commit()
            return {
                "msg": "订单批量删除成功",
                "deleted_count": len(found_ids)
            }
            
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"批量删除订单失败: {str(e)}") 